

<template>
  <view class="Mall4j container container-edit">
    <!--input列表 -->
    <view v-if="!isMap" class="input-box">
      <view class="section">
        <text>{{ i18n.recipient }}</text>
        <input :placeholder="i18n.recipientName" type="text" maxlength="15" :value="receiver" @input="onReceiverInput"></input>
      </view>
      <view class="section">
        <text>{{ i18n.mobilePhone }}</text>
        <input :placeholder="i18n.mobileNumberLength" type="number" maxlength="11" :value="mobile" @input="onMobileInput"></input>
      </view>
      <view class="section" @tap="translate">
        <text>{{ i18n.area }}</text>
        <view v-if="areaArray.length" class="pca">{{ province }} {{ city }} {{ area }}</view>
        <view v-else class="pca pca-pits">{{ i18n.selectProvinceCity }}</view>
        <template v-if="showPicker">
          <view class="animation-element-wrapper" :animation="animation" :style="'visibility:' + (show ? 'visible':'hidden')" @tap.stop="hiddenFloatView">
            <view class="animation-element" @tap.stop="nono">
              <text class="right-bt" @tap.stop="hiddenFloatView">{{ i18n.confirm }}</text>
              <view class="line" />
              <picker-view indicator-style="height: 50rpx;" :value="value" @change="bindChange" @tap.stop="nono">
                <!--省-->
                <picker-view-column>
                  <view v-for="(item, index) in provArray" :key="index">{{ item.areaName }}</view>
                </picker-view-column>
                <!--地级市-->
                <picker-view-column>
                  <view v-for="(item, index) in cityArray" :key="index">{{ item.areaName }}</view>
                </picker-view-column>
                <!--区县-->
                <picker-view-column>
                  <view v-for="(item, index) in areaArray" :key="index">{{ item.areaName }}</view>
                </picker-view-column>
              </picker-view>
            </view>
          </view>

        </template>
        <view class="arrow">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" />
        </view>
      </view>
      <view class="section">
        <text>{{ i18n.detailedAddress }}</text>
        <input class="addr" :placeholder="i18n.addressTips" type="text" :value="addr" maxlength="50" @input="onAddrInput"></input>
        <view class="arrow add-icon" @tap="selMap">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/submit-address.png" />
        </view>
      </view>
    </view>
    <!-- end input列表 -->
    <!-- 功能按钮 -->
    <view v-if="!isMap" class="btn-box">
      <view class="keep btn" @tap="onSaveAddr">
        <text>{{ i18n.saveAddress }}</text>
      </view>

      <view v-if="addrId!=0" class="clear btn" @tap="onDeleteAddr">
        <text>{{ i18n.deleteAddress }}</text>
      </view>
    </view>
    <!-- end 功能按钮 -->

    <!-- 腾讯地图组件 -->
    <view v-if="isMap" class="map">
      <view class="goOut" @click="isMap=false">返回</view>
      <iframe id="mapPage" width="100%" height="100%" frameborder="0" :src="`https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=${key}&referer=myapp`" />
      <!-- end 腾讯地图组件 -->
    </view>
  </view>
</template>

<script>
// pages/edit-address/edit-address.js
var http = require('../../utils/http.js')
var util = require('../../utils/util.js')
var index = [18, 0, 0]
var t = 0
var show = false
var moveY = 200

export default {

  components: {},
  props: {},
  data () {
    return {
      value: [0, 0, 0],
      provArray: [],
      cityArray: [],
      areaArray: [],
      province: '',
      city: '',
      area: '',
      provinceId: 0,
      cityId: 0,
      areaId: 0,
      receiver: '',
      mobile: '',
      addr: '',
      addrId: 0,
      animation: '',
      show: '',
      region: '',
      lat: '',
      lng: '',
      showPicker: false,
      key: 'L4DBZ-VSSKJ-GCDFX-KGBVR-KHZ2J-RNF2Q',
      isMap: false,
      isPosition: false
    }
  },
  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  onLoad: function (options) {
    uni.setNavigationBarTitle({
      title: options.addrId ? this.i18n.editShippingAddress : this.i18n.addShippingAddress
    })
    // this.initCityData(this.provinceId, this.cityId, this.areaId)
    if (options.addrId) {
      var params = {
        url: '/p/address/addrInfo/' + options.addrId,
        method: 'GET',
        data: {},
        callBack: res => {
          this.setData({
            provinceId: res.provinceId,
            cityId: res.cityId,
            areaId: res.areaId,
            receiver: res.receiver,
            mobile: res.mobile,
            addr: res.addr,
            addrId: options.addrId,
            lat: res.lat,
            lng: res.lng
          })
          this.initCityData(res.provinceId, res.cityId, res.areaId)
        }
      }
      http.request(params)
    } else {
      // this.initCityData(this.provinceId, this.cityId, this.areaId)
    }
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // 加载导航标题
    // uni.setNavigationBarTitle({
    //   title: this.i18n.editShippingAddress
    // })
  },
  onHide: function () {
    this.showPicker = false
  },
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: '50% 50%',
      duration: 0,
      timingFunction: 'ease',
      delay: 0
    })
    this.animation.translateY(200 + 'vh').step()
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },
  methods: {

    // 根据地图修改省份ID
    setProvinceId (province) {
      for (let i = 0; i < this.provArray.length; i++) {
        if (this.provArray[i].areaName === province) {
          const value = this.value
          value[0] = i
          this.setData({
            provinceId: this.provArray[i].areaId,
            value: value
          })
          this.getCityArray(this.provArray[i].areaId)
        }
      }
    },
    // 根据地图修改市ID
    setCityId (city) {
      for (let i = 0; i < city.length; i++) {
        if (city[i].areaName === this.city) {
          const value = this.value
          value[1] = i
          this.setData({
            cityId: city[i].areaId,
            value: value
          })
          this.getAreaArray(this.cityId)
        }
      }
    },
    // 根据地图修改区ID
    setAreaId (area) {
      for (let i = 0; i < area.length; i++) {
        if (area[i].areaName === this.area) {
          const value = this.value
          value[2] = i
          this.setData({
            areaId: area[i].areaId,
            value: [value[0], value[1], value[2]],
            isPosition: false
          })
          return uni.hideLoading()
        }
      }
    },

    /**
     * 腾讯地图以及微信小程序详细地址请求
     */
    selMap () {
      // const agree = this.getAgree()
      // if (!agree) {
      //   return
      // }
      const that = this
      // #ifdef H5
      this.isMap = true
      window.addEventListener('message', function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          that.addr = loc.poiaddress
          that.lat = loc.latlng.lat
          that.lng = loc.latlng.lng
          that.isMap = false
          util.area(loc.poiaddress, loc.poiname).then(res => {
            if (!res) return
            const addrReplacrstr = res[0].name + res[1].name + res[2].name
            that.addr = that.addr.replace(addrReplacrstr, '') || loc.poiname
            that.setData({
              value: [res[0].index, res[1].index, res[2].index],
              province: res[0].name,
              city: res[1].name,
              area: res[2].name,
              provinceId: res[0].areaId,
              cityId: res[1].areaId,
              areaId: res[2].areaId,
              provArray: res[3],
              cityArray: res[4],
              areaArray: res[5]
            })
            index = that.value
          })
          // var point = new plus.maps.Point(that.lng,that.lat);
          // plus.maps.Map.reverseGeocode(point,{},function(event){
          // var address = event.address; // 转换后的地理位置
          // var point = event.coord; // 转换后的坐标信息
          // var coordType = event.coordType; // 转换后的坐标系类型
          // 	console.log("Address:"+address);
          // },function(e){
          // 	console.log("Failed:"+JSON.stringify(e));
          // });

          // var params = {
          //   url: "/ws/geocoder/v1/",
          //   method: "GET",
          //   data: {
          //     location: that.lat + "," + that.lng,
          //     key: "OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77",
          //     output: "jsonp"
          //   },
          //   callBack: function (res) {
          //     console.log(res);
          //   }
          // };
          // http.request(params);

          // 使上面的地区选择栏跟着改变
          // let provinceIndex = loc.poiaddress.indexOf('省')
          // if(loc.poiaddress.slice(0,(provinceIndex)+1) !== ''){
          //   that.province = loc.poiaddress.slice(0,(provinceIndex)+1)
          // }

          // let cityIndex = loc.poiaddress.indexOf('市')
          // if(loc.poiaddress.slice(provinceIndex+1,cityIndex+1) !== ''){
          //   that.city = loc.poiaddress.slice(provinceIndex+1,cityIndex+1)
          // }

          // let areaIndex = loc.poiaddress.indexOf('区')
          // if(loc.poiaddress.slice(0,(provinceIndex)+1) !== ''){
          //   that.area = loc.poiaddress.slice(cityIndex+1,areaIndex+1)
          // }
          that.isPosition = true
          that.setProvinceId(that.province)
        }
      }, false)
      // #endif

      // #ifdef MP-WEIXIN
      uni.chooseLocation({
        success: function (res) {
          that.setMapData(res)
        },
        fail: function (failMsg) {
          // #ifdef MP-WEIXIN
          uni.getSetting({
            success (res) {
              if (!res.authSetting['scope.userLocation']) {
                console.log('f1')
                uni.authorize({
                  scope: 'scope.userLocation',
                  success () {
                    uni.chooseLocation({
                      success: function (res) {
                        that.setMapData(res)
                      }
                    })
                    console.log('success2')
                    that.isPosition = true
                    that.setProvinceId(that.province)
                  },
                  fail () {
                    uni.showToast({
                      title: that.i18n.authorityTips,
                      icon: 'none'
                    })
                  }
                })
              }
            }
          })
          // #endif
        }
      })
      // #endif
      // #ifdef APP-PLUS
      uni.chooseLocation({
        success: function (res1) {
          // that.setMapData(res);
          // console.log(res1)
          uni.getLocation({
            type: 'wgs84',
            geocode: true,
            success: function (res) {
              util.area(res1.address, res1.name).then(res2 => {
                if (!res2) return
                that.setData({
                  value: [res2[0].index, res2[1].index, res2[2].index],
                  province: res2[0].name,
                  city: res2[1].name,
                  area: res2[2].name,
                  provinceId: res2[0].areaId,
                  cityId: res2[1].areaId,
                  areaId: res2[2].areaId,
                  provArray: res2[3],
                  cityArray: res2[4],
                  areaArray: res2[5]
                })
                index = that.value
              })
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
                province: res.address.province,
                city: res.address.city,
                area: res.address.district,
                mapAddress: res1.address,
                mapAddrName: res1.name,
                addr: res1.address,
                isPosition: true
              })
              that.setProvinceId(that.province)
            }
          })
        }
      })
      // #endif
    },

    getAgree: function () {
      const that = this
      const agree = uni.getStorageSync('agreeAddress')
      if (agree) {
        uni.setStorageSync('agreeAddress', true)
        return true
      } else {
        uni.showModal({
          title: '提示',
          content: '添加地址要获取位置信息,是否授权该权限',
          success: function (res) {
            if (res.confirm) {
              uni.setStorageSync('agreeAddress', true)
              uni.showToast({
                title: '请再次点击同意',
                icon: 'none'
              })
              setTimeout(() => {
                that.selMap()
              })
              return true
            } else if (res.cancel) {
              uni.setStorageSync('agreeAddress', false)
              return false
            }
          }
        })
      }
    },

    initCityData: function (provinceId, cityId, areaId) {
      var ths = this
      var params = {
        url: '/p/area/listByPid',
        method: 'GET',
        data: {
          pid: 0
        },
        callBack: function (res) {
          ths.setData({
            provArray: res
          })
          if (provinceId) {
            for (var index in res) {
              if (res[index].areaId == provinceId) {
                ths.setData({
                  value: [Number(index), ths.value[1], ths.value[2]],
                  province: res[index].areaName
                })
              }
            }
          }
          ths.getCityArray(provinceId || res[0].areaId, cityId, areaId)
        }
      }
      http.request(params)
    },

    // 滑动事件
    bindChange: function (e) {
      var ths = this
      var val = e.detail.value // 判断滑动的是第几个column
      // console.log(1, val, index, ths.addr)

      // 若省份column做了滑动则定位到地级市和区县第一位
      if (index[0] != val[0]) {
        val[1] = 0
        val[2] = 0 // 更新数据
        // console.log('省份改变', this.provArray[val[0]].areaId)
        ths.getCityArray(this.provArray[val[0]].areaId) // 获取地级市数据
      } else {
        // 若省份column未做滑动，地级市做了滑动则定位区县第一位
        if (index[1] != val[1]) {
          val[2] = 0 // 更新数据

          ths.getAreaArray(this.cityArray[val[1]].areaId) // 获取区县数据
        }
      }

      index = val
      this.setData({
        value: [val[0], val[1], val[2]]
      })
      ths.setData({
        province: ths.provArray[ths.value[0]].areaName,
        city: ths.cityArray[ths.value[1]].areaName,
        area: ths.areaArray[ths.value[2]].areaName,
        provinceId: ths.provArray[ths.value[0]].areaId,
        cityId: ths.cityArray[ths.value[1]].areaId,
        areaId: ths.areaArray[ths.value[2]].areaId
      })
    },

    // 移动按钮点击事件
    translate: function (e) {
      if (t == 0) {
        moveY = 0
        show = false
        t = 1
      } else {
        moveY = 200
        show = true
        t = 0
      }
      this.initCityData(this.provinceId, this.cityId, this.areaId)
      this.setData({
        show: true,
        showPicker: true
      }) // this.animation.translate(arr[0], arr[1]).step();

      this.animationEvents(this, moveY, show)
    },

    // 隐藏弹窗浮层
    hiddenFloatView (e) {
      // console.log(e);
      moveY = 200
      show = true
      t = 0
      this.initCityData(this.provinceId, this.cityId, this.areaId)
      this.animationEvents(this, moveY, show)
    },

    // 动画事件
    animationEvents: function (that, moveY, show) {
      // console.log("moveY:" + moveY + "\nshow:" + show);
      that.animation = wx.createAnimation({
        transformOrigin: '50% 50%',
        duration: 400,
        timingFunction: 'ease',
        delay: 0
      })
      that.animation.translateY(moveY + 'vh').step()
      that.setData({
        animation: that.animation.export()
      })
    },

    /**
     * 根据省份ID获取 城市数据
     */
    getCityArray: function (provinceId, cityId, areaId) {
      var ths = this
      var params = {
        url: '/p/area/listByPid',
        method: 'GET',
        data: {
          pid: provinceId
        },
        callBack: function (res) {
          ths.setData({
            cityArray: res
          })
          if (ths.isPosition) {
            ths.setCityId(res)
            return
          }
          if (cityId) {
            for (var index in res) {
              if (res[index].areaId == cityId) {
                ths.setData({
                  value: [ths.value[0], Number(index), Number(ths.value[2])],
                  city: res[index].areaName
                })
              }
            }
          }

          ths.getAreaArray(cityId || res[0].areaId, areaId)
        }
      }
      http.request(params)
    },

    /**
      * 根据城市ID获取 区数据
      */
    getAreaArray: function (cityId, areaId) {
      var ths = this
      var params = {
        url: '/p/area/listByPid',
        method: 'GET',
        data: {
          pid: cityId
        },
        callBack: function (res) {
          ths.setData({
            areaArray: res
          })
          if (ths.isPosition) {
            ths.setAreaId(res)
            return
          }
          if (areaId) {
            for (var _index in res) {
              if (res[_index].areaId == areaId) {
                ths.setData({
                  value: [ths.value[0], ths.value[1], Number(_index)],
                  area: res[_index].areaName
                })
              }
            }

            index = ths.value
            ths.setData({
              province: ths.province,
              city: ths.city,
              area: ths.area,
              provinceId: ths.provinceId,
              cityId: ths.cityId,
              areaId: ths.areaId
            })
          } else {
            ths.setData({
              province: ths.provArray[ths.value[0]].areaName,
              city: ths.cityArray[ths.value[1]].areaName,
              area: ths.areaArray[ths.value[2]].areaName,
              provinceId: ths.provArray[ths.value[0]].areaId,
              cityId: ths.cityArray[ths.value[1]].areaId,
              areaId: ths.areaArray[ths.value[2]].areaId
            })
          }
        }
      }
      http.request(params)
    },
    bindRegionChange: function (e) {
      // console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        region: e.detail.value
      })
    },

    /**
     * 保存地址
     */
    onSaveAddr: function () {
      var ths = this
      var receiver = ths.receiver
      var mobile = ths.mobile
      var area = ths.area
      var addr = ths.addr
      var reg = /^\s+$/g
      if (!receiver.trim()) {
        ths.receiver = ''
        uni.showToast({
          title: ths.i18n.consigneeTips,
          icon: 'none'
        })
        return
      }
      if (!mobile) {
        uni.showToast({
          title: ths.i18n.enterMobileNumber,
          icon: 'none'
        })
        return
      }
      if (!area) {
        uni.showToast({
          title: ths.i18n.selectArea,
          icon: 'none'
        })
        return
      }
      if (!util.checkPhoneNumber(mobile)) {
        uni.showToast({
          title: ths.i18n.enterCorrectPhone,
          icon: 'none'
        })
        return
      }
      if (reg.test(addr)) {
        wx.showToast({
          title: ths.i18n.inputAllSpace,
          icon: 'none'
        })
        return
      }
      if (!addr || addr.length < 5) {
        uni.showToast({
          title: ths.i18n.enterCorrectAddress,
          icon: 'none'
        })
        return
      }

      var url = '/p/address/addAddr'
      var method = 'POST'

      if (ths.addrId != 0) {
        url = '/p/address/updateAddr'
        method = 'PUT'
      } // 添加或修改地址

      var params = {
        url: url,
        method: method,
        data: {
          receiver: ths.receiver,
          mobile: ths.mobile,
          addr: ths.addr,
          province: ths.province,
          provinceId: ths.provinceId,
          city: ths.city,
          cityId: ths.cityId,
          areaId: ths.areaId,
          area: ths.area,
          userType: 0,
          addrId: ths.addrId,
          lat: ths.lat, // 经度
          lng: ths.lng // 纬度
        },
        callBack: function (res) {
          uni.navigateBack({
            delta: 1
          })
        }
      }
      http.request(params)
    },
    onReceiverInput: function (e) {
      this.setData({
        receiver: e.detail.value
      })
    },
    onMobileInput: function (e) {
      this.setData({
        mobile: e.detail.value
      })
    },
    onAddrInput: function (e) {
      this.setData({
        addr: e.detail.value
      })
    },
    // 删除配送地址
    onDeleteAddr: function (e) {
      var ths = this
      uni.showModal({
        title: '',
        content: ths.i18n.deleteAddressTips,
        cancelText: ths.i18n.cancel,
        confirmText: ths.i18n.confirm,
        confirmColor: '#eb2444',

        success (res) {
          if (res.confirm) {
            var addrId = ths.addrId
            var params = {
              url: '/p/address/deleteAddr/' + addrId,
              method: 'DELETE',
              data: {},
              callBack: function (res) {
                uni.navigateBack({
                  delta: 1
                })
              }
            }
            http.request(params)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }

      })
    },

    /**
     * 获取经纬度
     */
    // chooseLocation: function (e) {
    //   var that = this;
    //   uni.chooseLocation({
    //     success: function (res) {
    //       console.log('succes1');
    //       console.log(res);
    //       that.setMapData(res);
    //     },
    //     fail: function (failMsg) {
    //       // #ifdef MP-WEIXIN
    //       uni.getSetting({
    //         success(res) {
    //           if (!res.authSetting['scope.userLocation']) {
    //             console.log("f1");
    //             uni.authorize({
    //               scope: 'scope.userLocation',
    //               success() {
    //                 uni.chooseLocation({
    //                   success: function (res) {
    //                     that.setMapData(res);
    //                     console.log(res)
    //                   }
    //                 });
    //                 console.log('success2');
    //               },
    //               fail() {
    //                 uni.showToast({
    //                   title: that.i18n.authorityTips,
    //                   icon: 'none'
    //                 });
    //               }
    //             });
    //           }
    //         }
    //       });
    //       // #endif
    //     },
    //     complete: function(res){
    //       console.log(res);
    //     }
    //   });
    // },

    setMapData (res) {
      this.lat = res.latitude // 纬度
      this.lng = res.longitude // 经度
      this.addr = res.address // 详细地址
      this.name = res.name // 详细地址

      console.log('腾讯/高德地图经纬度：', this.lng, '，', this.lat)
      util.area(res.address, res.name).then(res2 => {
        if (!res2) return
        this.setData({
          value: [res2[0].index, res2[1].index, res2[2].index],
          province: res2[0].name,
          city: res2[1].name,
          area: res2[2].name,
          provinceId: res2[0].areaId,
          cityId: res2[1].areaId,
          areaId: res2[2].areaId,
          provArray: res2[3],
          cityArray: res2[4],
          areaArray: res2[5]
        })
        index = this.value
      })
      this.qqMapTransBMap(this.lng, this.lat)
    }

  },

  // 将腾讯/高德地图经纬度转换为百度地图经纬度
  qqMapTransBMap: function (lng, lat) {
    const x_pi = 3.14159265358979324 * 3000.0 / 180.0
    const x = lng
    const y = lat
    const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
    const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
    const lngs = z * Math.cos(theta) + 0.0065
    const lats = z * Math.sin(theta) + 0.006

    this.lng = lngs
    this.lat = lats

    console.log('百度地图经纬度：', this.lng, '，', this.lat)
    return {
      lng: lngs,
      lat: lats
    }
  },

  // 空方法
  nono () {

  }
}

</script>
<style>
@import "./edit-address.css";
</style>
